/// <reference types="vite/client" />
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import menuTree from '@/router/baseMenuTree.json'
import useUserStore from '@/stores/user'

const modules = import.meta.glob('@/views/**/*.vue')

const loginPath = '/login'
const whiteList = [loginPath]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...getMenuTree()],
  scrollBehavior: (to) => {
    if (to.hash) {
      return {
        selector: to.hash,
        behavior: 'smooth',
      }
    }
    return { x: 0, y: 0, behavior: 'smooth' }
  },
})

router.beforeEach(async (to, from) => {
  console.log('to', to)
  console.log('from', from)
  const userStore = useUserStore()

  document.title = (to.meta.title as string) || ' '
  if (whiteList.includes(to.path)) {
    return true
  }

  try {
    if ((await userStore.checkUser()) === 2) {
      if (!to.meta.perms || userStore.hasPermission(to.meta.perms as string)) {
        return to.fullPath
      } else {
        return '/404'
      }
    }
    return true
  } catch (e) {
    /* 仅捕获错误就行，错误代表返回了401，会自动跳转到登录页 */
  }

  return {
    path: loginPath,
    query: {
      redirect: to.fullPath,
    },
  }
})

function getMenuTree(): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []
  for (const menu of menuTree) {
    const newRoute: RouteRecordRaw = {
      path: menu.path,
      meta: {
        title: menu.name,
        icon: menu.icon,
        hidden: menu.hidden === 1,
      },
      children: [],
    }

    if (menu.redirect) {
      newRoute.redirect = menu.redirect
    } else if (menu.component) {
      newRoute.component = modules[`/src/views${menu.component}.vue`]
    }

    routes.push(newRoute)
  }

  return routes
}

export default router
